/**
 * Created by Administrator on 2015/7/29.
 */
'use strict';
var C = require('../config/index');
var F = require('../common/function');
var _ = require('underscore');
_.str = require('underscore.string');
_.v = require('validator');
var _o2oServiceApi = require('../common/o2oServiceApi');
var o2oServiceApi = new _o2oServiceApi;
var o2oF = require('../common/o2ofunction');
var MUsers = require('../model/users.js');
var uid2 = require('uid2');
var md5 = require('md5');
var imgRule = require('../common/imgRule.js');
var redisCo = F.redisCo;
/**
 @todo API01 系统权限相关操作
 */
exports.premission = function *(Env) {
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  if (!(loginStatus.status == true )) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  let act = fields.act;
  let premissionName = fields.name || '';//权限名称
  let pCode = fields.pCode || '';//权限父id
  let type = fields.type || '';//1 总后台 2商家后台
  if (!_.v.isIn(type, [1, 2])) {
    return F.returnMsg(400, 'type只能是0或1', 1);
  }
  let manager = fields.manager || 0;
  if (manager != 1) {
    return F.returnMsg(400, '必须传入manager字段', 1);
  }
  if (act == 1)//增加系统权限
  {
    if (premissionName == '') {
      return F.returnMsg(400, '请输入你要增加的权限名称', 1);
    }
    if (!_.v.isIn(pCode, [0, 1])) {
      return F.returnMsg(400, 'pCode只能是0或1', 1);
    }
    let body = {act: 1};
    body.name = premissionName;
    body.pCode = pCode;
    body.type = type;

    let ret = yield o2oServiceApi.post('authority', 'permissAdd', 1, body);
    if (parseInt(ret['result']['error']) == 1 || ret.status == 400) {
      return F.returnMsg(400, '权限添加失败', 1);
    } else {
      return F.returnMsg(200, '权限添加成功', 1, ret['result']);
    }
  } else if (act == 2) {//获取系统所有权限列表
    let body = {act: 1, type: type};
    let ret = yield o2oServiceApi.post('authority', 'permissList', 1, body);
    if (parseInt(ret['result']['error']) == 1 || ret.status == 400) {
      return F.returnMsg(300, '没有有效的项', 1);
    }
    return F.returnMsg(200, '获取成功', 1, ret['result']);
  } else if (act == 3) {//添加一个角色，并设置权限 (如果该角色已存在,则覆盖权限)
    if (roleName == '' || permission == '') {
      return F.returnMsg(400, '请先设置角色名称并传入权限列表', 1);
    } else {
      let body = {act: 1};
      body.roleName = roleName;
      body.permission = permission;
      let ret = yield o2oServiceApi.post('role', 'add', 1, body);
      if (parseInt(ret['result']['error']) == 1 || ret.status == 400) {
        return F.returnMsg(400, '保存失败', 1);
      } else {
        return F.returnMsg(200, '保存成功', 1);
      }
    }
  } else if (act == 4) {//获取某个角色的权限图
    if (roleName == '') {
      return F.returnMsg(400, '请先输入你要查询的角色名称', 1);
    }
    let body = {act: 1};
    body.roleName = roleName;
    let ret = yield o2oServiceApi.post('role', 'permissions', 1, body);
    if (parseInt(ret['result']['error']) == 1 || ret.status == 400) {
      return F.returnMsg(300, '找不到指定的角色', 1);
    } else {
      return F.returnMsg(200, '获取成功', 1, ret['result']);
    }
  } else if (act == 5) {//查询某个角色是否有 指定的权限
    if (roleName == '' || groupName == '' || permission == '') {
      return F.returnMsg(400, '请先输入角色名称，权限组名称及权限名称', 1);
    }
    let body = {act: 1};
    body.roleName = roleName;
    body.groupName = groupName;
    body.permissionName = permission;

    let ret = yield o2oServiceApi.post('role', 'checkPermission', 1, body);
    if (parseInt(ret['result']['error']) == 1 || ret.status == 400) {
      return F.returnMsg(300, '找不到指定的角色', 1);
    } else {
      return F.returnMsg(200, '查找成功', 1, ret['result']);
    }
  }
};

/**
 @todo API02 模糊查询商品名称
 */
exports.getWareByName = function *(Env) {
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  if (!(loginStatus.status == true && F.isManager(loginStatus.groupid))) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  let act = fields.act;
  let wareName = fields.wareName || '';
  let page = fields.page || 1;
  let pageSize = fields.pagesize != undefined ? parseInt(fields.pagesize) : C.threadlist.pageSize;
  if (act == 1) {
    if (wareName == '') {
      return F.returnMsg(400, '请先输入商品名称', 1);
    }
    let body = {act: 3, name: wareName, page: page, pageSize: pageSize};
    let wareData = yield o2oServiceApi.post('ware', 'list', 1, body);
    if (parseInt(wareData['result']['error']) == 1 || wareData.status == 400) {
      return F.returnMsg(300, '没有找到相关的商品', 1);
    } else {
      return F.returnMsg(200, '查找成功', 1, wareData['result']);
    }
  }
};

/**
 @todo API03 角色相关API
 act  1:添加角色；2：更新角色；3：某商家的角色列表；4：角色权限详细
 */
exports.roleOperation = function *(Env) {
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  if (!(loginStatus.status == true)) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  //@todo 增加验证是否有该权限
  let act = fields.act;
  if (act == 1) {//1:添加角色
    let name = fields.name || '';
    if (name == '') {
      return F.returnMsg(400, '请先输入角色名称', 1);
    }
    let vid = fields.vid;
    if (!_.v.isInt(vid)) {
      return F.returnMsg(400, '供应商id只能接受数字', 1);
    }
    let body = {act: 1, name: name, vid: vid};

    let premissionArray = [];
    let permissionCodes = fields.permissionCodes;
    if (permissionCodes) {
      premissionArray = permissionCodes.split(',');
    }
    if (premissionArray.length > 0) {
      body.permissionCodes = premissionArray;
    }
    let roleResult = yield o2oServiceApi.post('authority', 'roleAdd', 1, body);
    if (parseInt(roleResult['result']['error']) == 1 || roleResult.status == 400) {
      return F.returnMsg(300, roleResult['message']['msg'], 1);
    } else {
      return F.returnMsg(200, '添加成功', 1, roleResult['result']);
    }
  } else if (act == 2) {//更新角色
    let body = {act: 1};
    let rid = fields.rid;
    if (!_.v.isInt(rid) || parseInt(rid) < 0) {
      return F.returnMsg(400, '角色Id只能输入数字', 1);
    } else {
      body.rid = rid;
    }

    let name = fields.name;
    if (name && !_.isEmpty(name)) {
      body.name = _.str.trim(name);
    }

    let status = fields.status;
    if (status != null) {
      if (_.v.isIn(status, [0, 1])) {
        body.status = status;
      } else {
        return F.returnMsg(400, 'status字段只能接受0或1', 1);
      }
    }

    let permissionCodes = fields.permissionCodes;
    if (permissionCodes) {
      if (!_.isArray(permissionCodes)) {
        return F.returnMsg(400, '权限参数只能输入数组', 1);
      } else {
        body.permissionCodes = permissionCodes;
      }
    }
    let roleResult = yield o2oServiceApi.post('authority', 'roleUpdate', 1, body);
    if (parseInt(roleResult['result']['error']) == 1 || roleResult.status == 400) {
      return F.returnMsg(300, roleResult['message']['msg'], 1);
    } else {
      return F.returnMsg(200, '更新成功', 1, roleResult['result']);
    }
  } else if (act == 3) {//获取某商家的角色列表
    let body = {act: 1, status: 1};
    let vid = fields.vid;//供应商id
    if (!_.v.isInt(vid)) {
      return F.returnMsg(400, '请输入正确的vendorId', 1);
    } else {
      body.vid = vid;
    }
    body.isPaging = 1;
    let page = fields.page || 1;
    let pageSize = fields.pageSize || 50;
    body.page = parseInt(page);
    body.pageSize = parseInt(pageSize);
    let roleResult = yield o2oServiceApi.post('authority', 'roleList', 1, body);
    if (parseInt(roleResult['result']['error']) == 1 || roleResult.status == 400) {
      return F.returnMsg(300, roleResult['message']['msg'], 1);
    } else {
      return F.returnMsg(200, '获取成功', 1, roleResult['result']);
    }
  } else if (act == 4) {//角色权限详细
    let rid = fields.rid;
    if (!_.v.isInt(rid)) {
      return F.returnMsg(400, '请输入正确的roleId', 1);
    }
    let body = {act: 1, rid: rid};
    let roleResult = yield o2oServiceApi.post('authority', 'roleDetail', 1, body);
    if (parseInt(roleResult['result']['error']) == 1 || roleResult.status == 400) {
      return F.returnMsg(300, roleResult['message']['msg'], 1);
    } else {
      return F.returnMsg(200, '获取成功', 1, roleResult['result']);
    }
  }
};

/**
 @todo API04 用户相关API
 act  1:添加用户角色匹配（isPaging决定是否返回总页数）；2：更新用户角色匹配；3：模糊查询某商家的用户列表；
 4：用户权限详细；5:根据手机号码精确查找用户；6：登录系统；7：登出系统
 */
exports.userOperation = function *(Env) {
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  let act = fields.act;
  if (!_.v.isIn(act.toString(), [6, 7])) {
    if (!loginStatus.status) {
      return F.returnMsg(401, '权限验证失败', 1);
    }
  }
  //@todo 增加验证是否有该权限
  if (act == 1) {//添加用户
    let rid = fields.rid;
    if (!_.v.isInt(rid)) {
      return F.returnMsg(400, '角色id只能接受数字', 1);
    }
    let uid = fields.uid;
    if (!_.v.isInt(uid)) {
      return F.returnMsg(400, '用户id只能接受数字', 1);
    }
    let name = fields.name;
    if (_.isEmpty(_.str.trim(name))) {
      return F.returnMsg(400, '必须输入使用者姓名', 1);
    }

    let primary = fields.primary;
    if (primary) {
      if (!_.v.isIn(primary, [0, 1])) {
        return F.returnMsg(400, 'primary字段只能接受0或1', 1);
      }
    }

    let permission_has_set =false;
    let role_has_set_permission = yield  o2oServiceApi.post('authority','roleDetail',1,{act:1,rid:rid});
    if(role_has_set_permission.status=200 && role_has_set_permission['result']['permissionCodes'] && role_has_set_permission['result']['permissionCodes'].length>0){
      permission_has_set = true;
    }
    if(!permission_has_set){
      return F.returnMsg(400, '角色权限未设置，请先设置权限', 1);
    }
    let body = {act: 1, rid: rid, uid: uid, primary: primary, name: name};
    //新增用户前，首先判断后台是否存在相同uid的用户
    //如果存在，并且status为0，则更新；
    //如果存在，并且status为1，则提示已经存在该用户
    let userData = yield o2oServiceApi.post('authority', 'userDetail', 1, {uid: uid, act: 1});
    let obj_user = {is_exist: false, is_valid: false};
    if (!(parseInt(userData['result']['error']) == 1 || userData.status == 400) && !_.isEmpty(userData['result'])) {
      obj_user.is_exist = true;
      if (userData['result']['status'] == 1) {
        obj_user.is_valid = true;
      } else {//如果该用户无效，则设为有效
        body.status = 1;
        body.id = userData['result']['id'];
      }
    }
    let roleResult = {};
    if (!obj_user.is_exist) {//后台不存在该用户则新增
      roleResult = yield o2oServiceApi.post('authority', 'userAdd', 1, body);
    } else {//后台已经存在该用户
      if (obj_user.is_valid) {
        return F.returnMsg(300, '该用户已经存在', 1);
      } else {//如果后台存在无效的用户，则更新
        roleResult = yield o2oServiceApi.post('authority', 'userUpdate', 1, body);
      }
    }
    if (parseInt(roleResult['result']['error']) == 1 || roleResult.status == 400) {
      return F.returnMsg(300, roleResult['message']['msg'], 1);
    } else {
      return F.returnMsg(200, '保存成功', 1, roleResult['result']);
    }
  } else if (act == 2) {//更新用户角色匹配
    let body = {act: 1};
    let rid = fields.rid;
    if (rid && parseInt(rid) > 0) {
      if (!_.v.isInt(rid)) {
        return F.returnMsg(400, '角色id只能接受数字', 1);
      } else {
        body.rid = parseInt(rid);
      }
    } else if (rid == null) {
      body.rid = 0;
    }
    let uid = fields.uid;
    if (uid) {
      if (!_.v.isInt(uid)) {
        return F.returnMsg(400, '用户id只能接受数字', 1);
      } else {
        body.uid = parseInt(uid);
      }
    }

    let id = fields.id || 'id';
    if (!_.v.isInt(id)) {
      return F.returnMsg(400, 'id字段只能接受数字', 1);
    } else {
      body.id = parseInt(id);
    }

    let status = fields.status;
    if (status != undefined) {
      if (_.v.isIn(status, [0, 1])) {
        body.status = status;
      } else {
        return F.returnMsg(400, 'status字段只能接受0或1', 1);
      }
    }


    let roleResult = yield o2oServiceApi.post('authority', 'userUpdate', 1, body);
    if (parseInt(roleResult['result']['error']) == 1 || roleResult.status == 400) {
      return F.returnMsg(300, roleResult['message']['msg'], 1);
    } else {
      let returnResult = _.pick(roleResult['result'], 'id', 'vid', 'mobile', 'primary', 'name', 'uid', 'rid');

      let userDetail = yield o2oServiceApi.post('authority', 'roleDetail', 1, {act: 3, rid: rid});
      if (parseInt(userDetail['result']['error']) == 1 || userDetail.status == 400) {
        returnResult.roleName = '';
      } else {
        returnResult.roleName = userDetail['result']['name'];
      }
      return F.returnMsg(200, '更新成功', 1, returnResult);
    }
  } else if (act == 3) {//某商家的用户列表
    let query_obj = {act: 1, status: 1};
    query_obj.isPaging = 1;

    let vid = fields.vid || 'vid';
    if (!_.v.isInt(vid)) {
      return F.returnMsg(400, '商家id字段只能接受数字', 1);
    } else {
      query_obj.vid = vid;
    }
    if (fields.rid && parseInt(fields.rid) != 0) {
      if (_.v.isInt(fields.rid)) {
        query_obj.rid = fields.rid;
      } else {
        return F.returnMsg(400, '角色id字段只能接受数字', 1);
      }
    }
    if (fields.exclude_rids && !_.isEmpty(fields.exclude_rids)) {
      query_obj.exclude = {};
      query_obj.exclude.rids = [];
      for (let rid of fields.exclude_rids.split(',')) {
        if (_.v.isInt(rid)) {
          query_obj.exclude.rids.push(rid);
        }
      }
    }
    if (fields.query) {
      query_obj.query = fields.query;
    }
    let page = fields.page || 1;
    let pageSize = fields.pageSize || 50;
    query_obj.page = parseInt(page);
    query_obj.pageSize = parseInt(pageSize);

    let userResult = yield o2oServiceApi.post('authority', 'userList', 1, query_obj);
    if (parseInt(userResult['result']['error']) == 1 || userResult.status == 400) {
      return F.returnMsg(300, userResult['message']['msg'], 1);
    } else {
      return F.returnMsg(200, '查找成功', 1, userResult['result']);
    }
  } else if (act == 4) {//4：用户权限详细
    let uid = fields.uid;
    if (uid) {
      if (!_.v.isInt(uid)) {
        return F.returnMsg(400, '用户id字段只能接受数字', 1);
      }
    }
    if (loginStatus.status) {
      uid = loginStatus.uid;
    }
    let userResult = yield o2oF.o2oGetUserPressiomInfo(uid);
    if (parseInt(userResult['result']['error']) == 1 || userResult.status == 400) {
      return F.returnMsg(300, userResult['message']['msg'], 1);
    } else {
      return F.returnMsg(200, '查找成功', 1, userResult['result']);
    }
  } else if (act == 5) {
    let mobile = fields.mobile;
    var userData = yield F.getUserByMobile(mobile);
    if (userData) {
      return F.returnMsg(200, '查找成功', 1, userData);
    } else {
      return F.returnMsg(300, '找不到对应的用户', 1);
    }
  } else if (act == 6) {//用户登录O2O管理后台
    let mobile = fields.mobile;
    let password = fields.password;
    let systemType = fields.systemType;
    let systemName = '总后台';
    if (systemType == 2) {
      systemName = '商家后台';
    }
    if (!F.isMobile(mobile)) {//判断手机号码格式是否正确
      return F.returnMsg(400, '手机号码格式不正确', 1);
    }

    if (password == undefined || _.str.trim(password) == '') {
      return F.returnMsg(400, '请输入密码', 1);
    }
    if (systemType == undefined || !_.v.isIn(systemType, [1, 2])) {
      return F.returnMsg(400, '管理后台类型无效，只能输入1或2', 1);
    }

    let attemptLimit = C.login.login_attemptLimit;
    let attempts = yield redisCo.get(C.login.login_attemptCountPrefix + mobile);
    attempts = attempts || 0;
    if (attempts >= attemptLimit) {
      return F.returnMsg(400, '尝试次数过多，请等待5分钟后再试', 1);
    }
    let userData = yield MUsers.getUser("uid,password,salt,mobile,groupid,nickname", "mobile=?", [mobile]);
    if (userData.length == 0) {
      return F.returnMsg(400, '你还没有注册', 1);
    }
    if (userData.length > 0 && userData[0]['groupid'] == 5) {
      return F.returnMsg(400, '无效账户', 1);
    } else if (userData.length > 0 && userData[0]['password'] == md5.digest_s(password + userData[0]['salt'])) {//用户在MySQL存在
      //判断在Mongo是否存在
      let Mongo_user_data = yield o2oServiceApi.post('authority', 'userDetail', 1, {act: 1, uid: userData[0]['uid']});
      if (parseInt(Mongo_user_data['result']['error']) == 1 || Mongo_user_data.status == 400) {
        return F.returnMsg(300, Mongo_user_data['message']['msg'], 1);
      } else {
        if (Mongo_user_data['result']['userMobile'] != mobile) {
          return F.returnMsg(400, '你还没有绑定' + systemName, 1);
        }
      }
      if (Mongo_user_data['result']['status'] != 1) {
        return F.returnMsg(400, '无效账户', 1);
      }
      //判断商家是否无效
      let vendor_data = yield o2oServiceApi.post('vendor', 'detail', 1, {act: 1, id: Mongo_user_data['result']['vid']});
      if (!vendor_data || vendor_data['result']['status'] != 1) {
        return F.returnMsg(400, '你所在的商家无效', 1);
      }
      if (Mongo_user_data['result']['vendorType'] != systemType) {
        return F.returnMsg(400, '你不是当前平台的用户', 1);
      }

      let newTokenkey = uid2(40);
      F.redisClient.hmset('siss:user:uid_' + userData[0]['uid'], 'uid', userData[0]['uid'], 'groupid',
        userData[0]['groupid'], 'nickname', userData[0]['nickname'], 'permissionCodes', Mongo_user_data['result']['permissionCodes'],
        'name', Mongo_user_data['result']['name'], 'roleName', Mongo_user_data['result']['roleName'],
        'primary', Mongo_user_data['result']['primary'], 'vid', Mongo_user_data['result']['vid'], 'vendorType', Mongo_user_data['result']['vendorType']
      );//保存会话
      F.redisClient.expire('siss:user:uid_' + userData[0]['uid'], C.session.ttl);
      F.redisClient.SETEX('siss:user:token_' + newTokenkey, C.session.ttl, userData[0]['uid']);
      yield MUsers.updateToken(userData[0]['uid'], newTokenkey);
      let face = F.generateFaceUrl(userData[0]['face'], userData[0]['uid'], 1);
      let minFace = F.generateFaceUrl(userData[0]['face'], userData[0]['uid']);
      return F.returnMsg(200, '登录成功', 3,
        {
          uid: userData[0]['uid'],
          nickname: userData[0]['nickname'],
          mobile: userData[0]['mobile'],
          face: face,
          minface: minFace,
          tokenkey: newTokenkey,
          permissionCodes: Mongo_user_data['result']['permissionCodes'],
          name: Mongo_user_data['result']['name'],
          roleName: Mongo_user_data['result']['roleName'],
          primary: Mongo_user_data['result']['primary'],
          id: Mongo_user_data['result']['id'],
          vid: Mongo_user_data['result']['vid'],
          vendorType: Mongo_user_data['result']['vendorType']
        });

    } else {
      F.redisClient.SETEX(C.login.login_attemptCountPrefix + mobile, C.login.login_lockInterval, (parseInt(attempts) + 1));
      return F.returnMsg(400, '手机号码或密码不匹配，还有 ' + (attemptLimit - attempts) + '次尝试机会', 1);
    }
  } else if (act == 7) {//用户登出系统
    if (loginStatus.status) {
      let key = 'siss:user:uid_' + loginStatus.uid;
      let temp = yield F.redisCo.EXISTS(key);
      if (temp == 1) {
        F.redisClient.DEL(key);
      }
    }
    return F.returnMsg(200, '登出成功', 1);
  }
};

/**
 @todo API05 商家管理相关API
 act  1:添加商家；2：编辑商家；3：根据id删除商家；4：绑定商家账号（先创建商家管理员角色,再将管理员角色的rid赋给user）
 5：商家列表；6：商家详情；
 */
exports.vendorOperation = function *(Env) {
  let fields = Env.I;
  let act = fields.act;
  //编辑跟删除时必须传入id字段
  let id = fields.id;
  if (_.v.isIn(act, [2, 3, 4, 6])) {
    if (id && _.v.isInt(id) > 0) {
      id = parseInt(id);
    } else {
      return F.returnMsg(400, '必须传入商家id字段', 1);
    }
  }
  if (act == 1) {//新增商家
    let vendor = _.pick(fields, 'name', 'disCodes', 'images', 'address', 'settled', 'officerName', 'officerTel', 'officerEmail',
      'financeName', 'financeTel', 'serviceName', 'serviceTel', 'licenseType', 'licenseNo', 'licenseName', 'licenseExpired', 'licenseImage', 'licenseIDImgFront', 'licenseIDImgBack',
      'bankName', 'bankBranchName', 'bankAddress', 'cardName', 'cardNo');
    let vendor_add = require('./o2o/vendor/add');
    return yield vendor_add.vendor_add(vendor);
  } else if (act == 2) {//编辑商家
    let vendor = _.pick(fields, 'id', 'name', 'disCodes', 'images', 'address', 'settled', 'officerName', 'officerTel', 'officerEmail',
      'financeName', 'financeTel', 'serviceName', 'serviceTel', 'licenseType', 'licenseNo', 'licenseName', 'licenseExpired', 'licenseImage', 'licenseIDImgFront', 'licenseIDImgBack',
      'bankName', 'bankBranchName', 'bankAddress', 'cardName', 'cardNo');
    vendor.id = parseInt(vendor.id);
    let vendor_update = require('./o2o/vendor/update');
    return yield vendor_update.vendor_update(vendor);
  } else if (act == 3) {//删除商家，将商家的状态改为0
    let vendorResult = yield o2oServiceApi.post('vendor', 'update', 1, {id: id, status: 0, act: 1});
    if (parseInt(vendorResult['result']['error']) == 1 || vendorResult.status == 400) {
      return F.returnMsg(300, vendorResult['message']['msg'], 1);
    } else {
      return F.returnMsg(200, '保存成功', 1, vendorResult['result']);
    }
  } else if (act == 4) {//绑定商家角色,1.检查要绑定的用户是否已经被其他商家绑定；2.初始化角色（如果商家角色还没初始化）；3.绑定商家管理员角色给即将要绑定的用户
    let mobile = fields.mobile;
    if (!F.isMobile(mobile)) {
      return F.returnMsg(400, '电话格式无效，请检查', 1);
    }
    let sellUserId = fields.sellUserid;
    let bind_user = require('./o2o/vendor/bind_user');
    return yield bind_user.bind_user(id, mobile, sellUserId);

  } else if (act == 5) {//商家列表
    let obj_query = {act: 1, status: 1};
    let more = fields.more;
    if (more && parseInt(more) == 1) {
      obj_query.act = 2;
    }
    let type = fields.type;
    if (type != undefined && parseInt(type) > 0) {
      obj_query.type = type;
    }
    let query = fields.query;
    if (query != undefined && !_.isEmpty(query)) {
      obj_query.query = query;
    }
    let settled = fields.settled;
    if (settled != undefined && _.v.isIn(settled, [0, 1])) {
      obj_query.settled = settled;
    }
    let district = fields.district;
    if (district && _.v.isInt(district) && parseInt(district) > 0) {
      obj_query.district = parseInt(district);
    }
    let page = fields.page || 1;
    let pageSize = fields.pageSize || 50;
    obj_query.page = parseInt(page);
    obj_query.pageSize = parseInt(pageSize);
    let isPaging = fields.isPaging;
    if (isPaging && parseInt(isPaging) == 1) {
      obj_query.isPaging = 1;
    }
    let list = require('./o2o/vendor/list');
    return yield list.vendor_list(obj_query);

  } else if (act == 6) {//商家详情
    let id = fields.id || 0;
    let obj_query = {act: 1};
    if (id && parseInt(id) > 0) {
      obj_query.id = parseInt(id);
    } else {
      return F.returnMsg(400, 'id字段无效', 1);
    }
    let vendorResult = yield o2oServiceApi.post('vendor', 'detail', 1, obj_query);
    if (parseInt(vendorResult['result']['error']) == 1 || vendorResult.status == 400) {
      return F.returnMsg(300, vendorResult['message']['msg'], 1);
    } else {
      let vendor_F = require('./o2o/vendor/vendor_common');
      yield vendor_F.getUpYunImage(vendorResult['result']);
      return F.returnMsg(200, '查找成功', 1, vendorResult['result']);
    }
  }
};

/**
 @todo API06 机构管理相关API
 act  1:添加机构；2：修改机构信息；3：商家后台根据id提交删除机构；4：机构详情；5：商家后台的机构列表；6:根据商家获取所有店长列表；7：添加或绑定店长
 8:根据商家id获取机构所在的省市;9:根据地址编码获取机构列表;10：总后台的机构删除列表；11：总后台删除机构
 */
exports.organizationOperation = function *(Env) {
  let fields = Env.I;
  let act = fields.act;
  let loginStatus = fields.loginStatus;
  // 身份验证
  if (!loginStatus.status) {
    return F.returnMsg('401', '身份验证失败', 3);
  }

  let key_validate_array = ['vendorid','name', 'image', 'shopKeeper', 'shopKeeperEmail', 'shopKeeperTel', 'tel', 'address',
    'loc', 'district', 'openTime', 'closeTime', 'graphicDetails'];
  //编辑跟删除时必须传入id字段
  let id = fields.id;
  if (_.v.isIn(act, [2, 3, 4, 7,11])) {
    if (id && _.v.isInt(id) > 0) {
      id = parseInt(id);
    } else {
      return F.returnMsg(400, '必须传入机构id字段', 1);
    }
  }
  if (act == 1) {//新增机构
    let obj_organization = _.pick(fields, 'vendorid','name', 'image', 'shopKeeper', 'shopKeeperEmail', 'shopKeeperTel', 'tel', 'address',
      'loc', 'district', 'openTime', 'closeTime', 'graphicDetails');
    let organization_add = require('./o2o/organization/add');
    return yield organization_add.add_organization(obj_organization, key_validate_array);
  } else if (act == 2) {//编辑机构
    let obj_organization = _.pick(fields,'name', 'image', 'shopKeeper', 'shopKeeperEmail', 'shopKeeperTel', 'tel', 'address',
      'loc', 'district', 'openTime', 'closeTime', 'graphicDetails', 'id');
    let organization_update = require('./o2o/organization/update');
    return yield organization_update.organization_update(obj_organization, key_validate_array);
  } else if (act == 3) {//删除机构(商家后台用)
    let deleteDescription = fields.deleteDescription;
    if (deleteDescription == undefined || _.isEmpty(deleteDescription)) {
      return F.returnMsg(400, '删除理由不能为空', 1);
    }
    let organizationResult = yield o2oServiceApi.post('shop', 'update', 1, {id: id, status: 2, act: 1,deleteDescription:deleteDescription,submitTime:new Date()});
    if (parseInt(organizationResult['result']['error']) == 1 || organizationResult.status == 400) {
      return F.returnMsg(300, organizationResult['message']['msg'], 1);
    } else {
      return F.returnMsg(200, '提交成功', 1, {id:id,status:2});
    }
  } else if (act == 4) {//机构详情
    let organizationResult = yield o2oServiceApi.post('shop', 'detail', 1, {act: 1, id: id});
    if (parseInt(organizationResult['result']['error']) == 1 || organizationResult.status == 400) {
      return F.returnMsg(300, organizationResult['message']['msg'], 1);
    } else {
      let organization_F = require('./o2o/organization/organization_common');
      yield organization_F.getUpYunImage(organizationResult['result']);
      organizationResult['result'] = yield organization_F.deleteUnuselessFields(organizationResult['result']);
      return F.returnMsg(200, '查找成功', 1, organizationResult['result']);
    }
  }
  else if (act == 5) {//查找商家下面的机构列表
    let obj_query = {act: 6, status: 1};
    if (fields.vid == undefined || !_.v.isInt(fields.vid)) {
      return F.returnMsg('400', '请先输入有效的商家id', 3);
    }
    obj_query.vendorid = parseInt(fields.vid);

    obj_query.vendorType = loginStatus.vendorType;
    let query = fields.query;
    if (query != undefined && !_.isEmpty(query)) {
      obj_query.query = query;
    }
    let settled = fields.settled;
    if (settled != undefined && _.v.isIn(settled, [0, 1])) {
      obj_query.settled = settled;
    }
    let district = fields.district;
    if (district && _.v.isInt(district) && parseInt(district) > 0) {
      obj_query.district = parseInt(district);
    }
    let page = fields.page || 1;
    let pageSize = fields.pageSize || 50;
    obj_query.page = parseInt(page);
    obj_query.pageSize = parseInt(pageSize);
    obj_query.isPaging = 1;
    obj_query.status = 1;

    //let isPaging = fields.isPaging;
    //if (isPaging && parseInt(isPaging) == 1) {
    //  obj_query.isPaging = 1;
    //}
    let list = require('./o2o/organization/list');
    return yield list.organization_list(obj_query);
  }
  else if (act == 6) {//查找商家下面的所有店长
    let vid = parseInt(fields.vid);
    if (vid == undefined || !_.v.isInt(vid)) {
      return F.returnMsg('400', '必须传入商家id', 1);
    }
    let type = fields.type == undefined ? 1:parseInt(fields.type); //type 1 获取指定商家所有店长列表，2 获取指定商家可用列表，同时保留指定机构已绑定的那条列表
    if(!_.v.isIn(type,[1,2,3])){
      return F.returnMsg('400', 'type只能是1或者2或者3', 1);
    }
    if(type ==2 || type == 3){
      if(fields.sid == undefined || !(_.v.isInt(fields.sid) && parseInt(fields.sid)>0)){
        return F.returnMsg('400', 'sid必须存在并且是整数', 1);
      }
      var sid = fields.sid;
    }
    if(type == 3){
      fields.name = fields.name == undefined ? '':_.str.trim(fields.name);
    }

    let role_store_keeper_id = 0;
    let vendorList = yield o2oServiceApi.post('authority', 'roleList', 1, {act: 1, vid: vid});
    if (parseInt(vendorList['result']['error']) == 1 || vendorList.status == 400) {
      return F.returnMsg(300, vendorList['message']['msg'], 1);
    } else {
      let store_keeper_role = _.filter(vendorList['result'], function (role) {
        return role.name == '店长';
      });
      if (store_keeper_role == undefined || _.isEmpty(store_keeper_role)) {
        return F.returnMsg('400', '该商家还没有创建店长角色', 3);
      }
      let role_store_keeper_id = store_keeper_role[0].rid;
      let  userList ={};
      if(type == 3){
         userList = yield o2oServiceApi.post('authority', 'userList', 1, {
          act: 2,
          vid: vid,
          rid: role_store_keeper_id,
          query:fields.name
        });
        //查找指定sid已绑定店长的记录
          let curuserList = yield  o2oServiceApi.post('authority','userList',1,{act:3,queryObj:{vid:vid,sid:sid,primary:0}});
          if(!(parseInt(curuserList['result']['error']) == 1 || curuserList.status == 400)){
            if(curuserList['result'].length>0){
              for(let i in  userList['result']){
                if(userList['result'][i]['sid'] == curuserList['result'][0]['sid']){
                  userList['result'].splice(i,1);
                  break;
                }
              }
            }
            userList['result'] = _.union(userList['result'],curuserList['result']);
          }
      }else{
         userList = yield o2oServiceApi.post('authority', 'userList', 1, {
          act: 3,
          queryObj: {vid: vid, rid: role_store_keeper_id, status: 1}
        });
      }
      if (parseInt(userList['result']['error']) == 1 || userList.status == 400) {
        return F.returnMsg(300, userList['message']['msg'], 1);
      } else {
        if (!userList['result'] || userList['result'].length == 0) {
          return F.returnMsg(300, '该商家还没有关联任何店长', 1);
        } else {
          for(let i in userList['result']){
            userList['result'][i] = _.pick(userList['result'][i], 'uid', 'name','sid');
            userList['result'][i]['isbind'] =userList['result'][i]['sid']>0? 1:0;
          }
          if(type == 2 || type == 3){
              let current_user = _.filter(userList['result'],function(obj){
                return obj.sid == sid;
              });
              userList['result'] = _.filter(userList['result'],function(item){
                return  item.sid ==0;
              });
             userList['result'] =_.union(current_user,userList['result']);
          }
          return F.returnMsg(200, '成功', 1, userList['result']);
        }
      }
    }
  } else if (act == 7) {//绑定，重新绑定店长
    let uid = fields.uid;
    if (uid == undefined || !_.v.isInt(uid)) {
      return F.returnMsg(400, '用户id输入无效', 1);
    }
    uid = parseInt(uid);
    let bind_user = require('./o2o/organization/bind_user');
    return yield bind_user.bind_user(id, uid);
  } else if (act == 8) {//获取商家机构所在的城市列表
    let vendorid = fields.vid;
    if (vendorid == undefined || !_.v.isInt(vendorid)) {
      return F.returnMsg(400, '商家id输入无效', 1);
    }
    let vendorCityData = yield o2oServiceApi.post('shop', 'getDistrict', 1, {act: 1, vendorid: vendorid});
    if (parseInt(vendorCityData['result']['error']) == 1 || vendorCityData.status == 400) {
      return F.returnMsg(300, vendorCityData['message']['msg'], 1);
    } else {
      if (vendorCityData['result'].length == 0) {
        return F.returnMsg(300, '该商家还没有机构进驻', 1);
      } else {
        return F.returnMsg(200, '成功', 1, vendorCityData['result']);
      }
    }
  } else if (act == 9) {//根据地址编码获取机构列表
    let districtCode = fields.districtCode;
    if (districtCode == undefined || !_.v.isInt(districtCode)) {
      return F.returnMsg(400, '地址编码无效', 1);
    }
    let vendorid = fields.vid;
    if (vendorid == undefined) {
      return F.returnMsg(400, '商家编码无效', 1);
    }
    let obj_query = {act: 5, vendorid: vendorid, districtCode: districtCode, status: 1};
    let organizationData = yield o2oServiceApi.post('shop', 'list', 1, obj_query);
    if (parseInt(organizationData['result']['error']) == 1 || organizationData.status == 400) {
      return F.returnMsg(300, organizationData['message']['msg'], 1);
    } else {
      if (organizationData['result'].length == 0) {
        return F.returnMsg(300, '该商家在该城市没有机构', 1);
      } else {
        return F.returnMsg(200, '成功', 1, organizationData['result']);
      }
    }
  }else if(act == 10){
    let organization_delete_list = yield o2oServiceApi.post('shop', 'list', 1, {act: 8});
    if(parseInt(organization_delete_list['result']['error'])==1 || organization_delete_list.status == 400){
      return F.returnMsg(300, organization_delete_list['message']['msg'], 1);
    }else{
      if (organization_delete_list['result'].length == 0) {
        return F.returnMsg(300, '没有删除机构的申请', 1);
      } else {
        return F.returnMsg(200, '成功', 1, organization_delete_list['result']);
      }
    }
  }else if(act == 11){
    let organizationResult = yield o2oServiceApi.post('shop', 'update', 1, {id: id, status: 0, act: 1});
    if (parseInt(organizationResult['result']['error']) == 1 || organizationResult.status == 400) {
      return F.returnMsg(300, organizationResult['message']['msg'], 1);
    } else {
      return F.returnMsg(200, '删除成功', 1, {id:id,status:0});
    }
  }
};

/**后台项目管理API
 * act:1 后台商家项目列表；2 新增项目版本；3：编辑项目；4：项目详情；5：
 */
exports.wareAdd = function *(Env){
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  // 身份验证
  if (!loginStatus.status) {
    return F.returnMsg('401', '身份验证失败', 3);
  }
  let key_validate_array = ['categories','shops', 'images', 'services', 'totalQuantity', 'offLineTtime', 'graphicDetails', 'onLineTime', 'price',
    'marketPrice', 'name', 'vendorid'];
  let ware=_.pick(fields,'categories','shops', 'images', 'services', 'totalQuantity', 'offLineTtime', 'graphicDetails', 'onLineTime', 'price',
    'marketPrice', 'name', 'vendorid');
  let ware_add = require('./o2o/ware/add');
  return yield ware_add.add_ware(ware, key_validate_array);
};
exports.wareUpdate= function *(Env){
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  // 身份验证
  if (!loginStatus.status) {
    return F.returnMsg('401', '身份验证失败', 3);
  }

  let key_validate_array = ['categories','shops', 'images', 'services', 'totalQuantity', 'offLineTtime', 'graphicDetails', 'onLineTime', 'price',
    'marketPrice', 'name', 'vendorid','id'];
  let ware=_.pick(fields,'categories','shops', 'images', 'services', 'totalQuantity', 'offLineTtime', 'graphicDetails', 'onLineTime', 'price',
    'marketPrice', 'name', 'vendorid','id');
  let ware_update = require('./o2o/ware/update');

  return yield ware_update.ware_update(ware, key_validate_array);
};
/**后台项目管理API
 * act:  2： 后台商家详情中的项目列表
 *       3: 后台项目审核中的最新列表
 *       4: 后台查询历史版本
 *      5: 总后台删除管理中的项目删除列表
 */
exports.wareList = function *(Env){
  let fields = Env.I;
  let loginStatus=fields.loginStatus;
  // 身份验证
  if (!loginStatus.status) {
    return F.returnMsg('401', '身份验证失败', 3);
  }
  let act = parseInt(fields.act);
  let obj_query = {act: act};
  obj_query.vendorid = parseInt(vendorid);
  let page = fields.page || 1;
  let pageSize = fields.pageSize || 50;
  obj_query.page = parseInt(page);
  obj_query.pageSize = parseInt(pageSize);
  obj_query.isPaging = 1;
  let ware_list = require('./o2o/ware/list');
  switch (act){
    case 2://2： 后台商家详情中的项目列表
      var vendorid = fields.vendorid;
      if (vendorid == undefined || !_.v.isInt(vendorid)) {
        return F.returnMsg('400', '请先传入vendorId', 3);
      }
      obj_query.vendorid = vendorid;
      return yield ware_list.wareListForVendorDetail(obj_query);
    case 3: //3: 后台项目审核中的最新列表
      if (fields.query && !_.isEmpty(query)) {
        obj_query.query = fields.query;
      }
      if(fields.submitTime && _.v.isDate(fields.submitTime)){
        obj_query.submitTime=fields.submitTime;
      }
      if(fields.auditStatus && _.v.isIn(fields.auditStatus ,[1,2,3,4])){
        obj_query.auditStatus=fields.auditStatus;
      }
      return yield ware_list.wareAuditList(obj_query);
    case 4:// 4: 后台查询历史版本
      var wareid=fields.wareid;
      if (wareid == undefined || !_.v.isInt(wareid)) {
        return F.returnMsg('400', 'wareid字段无效，请检查', 3);
      }
      obj_query.wareid = wareid;
      return yield ware_list.wareHistoryList(obj_query);
    case 5:// 5 总后台删除管理中的项目删除列表
      if (fields.query && !_.isEmpty(fields.query)) {
        obj_query.query = fields.query;
      }
      if(fields.submitTime && _.v.isDate(fields.submitTime)){
        obj_query.submitTime=fields.submitTime;
      }
      return yield ware_list.wareDeleteList(obj_query);
  }
};

/**后台项目管理API
 * act:  1：项目详情；2：提交审核； 3： 项目上架
 *       4：项目下架 5：提交删除项目;6:总后台审核项目
 *       7: 总后台删除项目
 */
exports.wareOperation = function *(Env) {
  let fields = Env.I;
  let act = fields.act;
  let loginStatus = fields.loginStatus;
  // 身份验证
  if (!loginStatus.status) {
    return F.returnMsg('401', '身份验证失败', 3);
  }
  let id = fields.id;
  if (_.v.isIn(act, [2, 3,4,5,6,7])) {
    if (id == undefined || !_.v.isInt(id)) {
      return F.returnMsg('400', 'id字段无效，请检查', 3);
    }
  }
  id = parseInt(id);
  if (act == 1) {//项目详情
    let ware_version_detail = yield o2oServiceApi.post('ware', 'detailVersion', 1, {id: id, act: 1});
    if (parseInt(ware_version_detail['result']['error']) == 1 || ware_version_detail.status == 400) {
      return F.returnMsg(300,ware_version_detail['message']['msg'],1);
    }else{
      let ware_F = require('./o2o/ware/ware_common');
      ware_version_detail=ware_F.deleteUnuselessFields(ware_version_detail['result']);
      ware_F.getUpYunImage(ware_version_detail);
      return F.returnMsg(200,'获取成功',1,ware_version_detail);
    }
  } else if (act == 2) {//项目提交审核
    let ware_version_detail = yield o2oServiceApi.post('ware', 'detailVersion', 1, {act: 1, id: id});
    if (ware_version_detail && ware_version_detail['result'] != undefined) {
      if (!_.v.isIn(ware_version_detail['result']['auditStatus'], [1, 3])) {
        if (ware_version_detail['result']['auditStatus'] == 4) {
          return F.returnMsg(200, '该项目版本正在等待审核，不能重复提交', 1);
        } else if (ware_version_detail['result']['auditStatus'] == 2) {
          return F.returnMsg(200, '该项目版本已通过审核，不能重复提交', 1);
        }
      }
    }
    let obj_ware_update = {act: 1, id: id, auditStatus: 4,submitTime:new Date()};
    let ware_update_result = yield o2oServiceApi.post('ware', 'updateVersion', 1, obj_ware_update);
    if (parseInt(ware_update_result['result']['error']) == 1 || ware_update_result.status == 400) {
      return F.returnMsg(300, ware_update_result['message']['msg'], 1);
    } else {
      return F.returnMsg(200, '提交成功', 1, {id: id, auditStatus: 4});
    }
  }  else if (act == 3) {//项目上架
    let ware_F = require('./o2o/ware/ware_common');
    let msg =yield ware_F.wareOnSell(id);
    if (msg == 'done') {
      return F.returnMsg(200, '上架成功', 1, {id: id, isSell: 1});
    } else {
      return F.returnMsg(200, '上架失败,原因如下:' + msg, 1);
    }
  } else if (act == 4) {//项目下架
    let ware_F = require('./o2o/ware/ware_common');
    let msg =yield ware_F.wareSoldOut(id);
    if (msg == 'done') {
      return F.returnMsg(200, '下架成功', 1, {id: id, isSell: 0});
    } else {
      return F.returnMsg(200, '下架失败,原因如下:' + msg, 1);
    }
  }else if(act ==5) {//提交删除项目
    let deleteDescription = fields.deleteDescription;
    if (deleteDescription == undefined || _.isEmpty(deleteDescription)) {
      return F.returnMsg(400, '请先填写删除原因', 1);
    }
    let ware_version_update = yield o2oServiceApi.post('ware','updateVersion',1,{id: id, act: 1, deleteDescription: deleteDescription,status:2,submitTime:new Date()});
    if(parseInt(ware_version_update['result']['error'])==1 || ware_version_update.status == 400){
      return F.returnMsg(300,ware_version_update['message']['msg'],1);
    }else{
      return F.returnMsg(200, '删除请求已发送，请等待审核', 1);
    }
  }else if(act ==6){//总后台审核项目
    let auditStatus=fields.auditStatus;
    if(!_.v.isIn(auditStatus,[2,3])){//2:审核通过；3：审核不通过
      return F.returnMsg(400, '审核状态传入参数有误，请检查', 1);
    }
    let comment=fields.comment||'';
    if(auditStatus==3){//审核不通过
      if(comment==undefined || _.isEmpty(comment)){
        return F.returnMsg(400, '请传入审核失败的原因', 1);
      }
    }else if(auditStatus == 2){
      comment = '';
    }
    let ware_version_detail = yield o2oServiceApi.post('ware', 'detailVersion', 1, {act: 1, id: id});
    if (ware_version_detail && ware_version_detail['result'] != undefined) {
      if (!_.v.isIn(ware_version_detail['result']['auditStatus'], [4])) {
        return F.returnMsg(200, '该记录还没提交，不能审核', 1);
      }
    }
    let obj_ware_update = {act: 1, id: id, auditStatus: auditStatus,auditLog:{auditStatus:auditStatus,comment:comment}};
    let ware_update_result = yield o2oServiceApi.post('ware', 'updateVersion', 1, obj_ware_update);
    if (parseInt(ware_update_result['result']['error']) == 1 || ware_update_result.status == 400) {
      return F.returnMsg(300, ware_update_result['message']['msg'], 1);
    } else {
      return F.returnMsg(200, '提交成功', 1, {id: id, auditStatus: auditStatus,comment:comment});
    }
  }else if(act == 7){//总后台删除项目
    let ware_delete = yield o2oServiceApi.post('ware', 'updateVersion', 1, {id: id, act: 1,status:0});
    if (parseInt(ware_delete['result']['error']) == 1 || ware_delete.status == 400) {
      return F.returnMsg(300,ware_delete['message']['msg'],1);
    }else{
      return F.returnMsg(200,'删除成功',1);
    }
  }
};

/**
 @用于后台更改商家，机构，商品后的回调函数
 函数名：o2oImgCallback
 * 参数：无
 * 返回：对应的o2o 实体
 */
exports.o2oImgCallback = function *(Env, data) {
  // 是否内部调用
  let fields;
  let loginStatus = Env.I.loginStatus;

  if (!data) {
    if (!loginStatus.status) {
      return F.returnMsg(401, '权限注册失败', 3);
    }
    fields = Env.I;
  } else { // 内部调用
    fields = data;
  }
  let id = fields.id;//实体的id
  if (id == undefined || !_.v.isInt(id)) {
    return F.returnMsg(400, '传入的id无效', 3);
  } else {
    id = parseInt(id);
  }
  let act = fields.act;
  if (act == 1) {//新增商家或编辑
    let vendorResult = yield o2oServiceApi.post('vendor', 'update', 1, {id: id, status: 1, act: 1});
    if (parseInt(vendorResult['result']['error']) == 1 || vendorResult.status == 400) {
      return F.returnMsg(300, vendorResult['message']['msg'], 1);
    } else {
      let vendor_F = require('./o2o/vendor/vendor_common');
      yield vendor_F.getUpYunImage(vendorResult['result']);
      return F.returnMsg(200, '成功', 1, vendorResult['result']);
    }
  } else if (act == 2) {//新增或编辑机构
    let organizationResult = yield o2oServiceApi.post('shop', 'update', 1, {id: id, status: 1, act: 1});
    if (parseInt(organizationResult['result']['error']) == 1 || organizationResult.status == 400) {
      return F.returnMsg(300, organizationResult['message']['msg'], 1);
    } else {
      let organization_F = require('./o2o/organization/organization_common');
      yield organization_F.getUpYunImage(organizationResult['result']);
      return F.returnMsg(200, '成功', 1, organizationResult['result']);
    }
  }else if(act ==3){//新增或编辑项目版本
    let wareResult = yield o2oServiceApi.post('ware', 'update', 1, {id: id, status: 1, act: 1});
    if (parseInt(wareResult['result']['error']) == 1 || wareResult.status == 400) {
      return F.returnMsg(300, wareResult['message']['msg'], 1);
    } else {
      let ware_F = require('./o2o/ware/ware_common');
      yield ware_F.getUpYunImage(wareResult['result']);
      return F.returnMsg(200, '成功', 1, wareResult['result']);
    }
  }
};

/**商家，机构，产品的图文详情图片上传API
 *
 */
exports.getSignForO2O = function*(Env) {
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  if (!(loginStatus.status == true)) {
    return F.returnMsg(401, '权限验证失败', 1);
  }
  var fileName = F.timestamp() + F.getRandom(4).toString();
  var upyun = {
    type: 8,
    filename: fileName
  };
  var returnData = yield F.getUpyunSign(upyun);
  returnData.fileUrl = C.upyun.h5pic_url + '/' + fileName + '.jpg';
  return F.returnMsg(200, '成功', 3, returnData);
};

/**
 * @获取订单相关API
 * act  1 获取当前商家下所有的订单列表 2 根据订单id获取订单详情  3 根据订单id获取用户所有状态下瓷肌券列表  4 根据瓷肌券码获取瓷肌券详情  5.根据瓷肌券码验证瓷肌券
 *      6 获取已验证的瓷肌券列表 type=2【商家后台】获取商家已验证的瓷肌券列表记录  type=1 【总后台】获取全部已验证瓷肌券列表记录
 * @param Env
 */
exports.orderOperation = function *(Env){
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  //if (!loginStatus.status){
  //  return F.returnMsg(401, '权限验证失败', 1);
  //}
  let act = fields.act;
  if(_.v.isIn(act,[1,2,3])){
      if(!(fields.id && _.v.isInt(fields.id) && fields.id>0)){
        return F.returnMsg(400,'请先传入id参数！',1);
      }
  }
  if(_.v.isIn(act,[4,5,7])){
    if(!(fields.ticket_code && _.v.isInt(fields.ticket_code) && fields.ticket_code>0)){
      return F.returnMsg(400,'请先传入瓷肌券码！',1);
    }
  }

  if(act == 1){ //通过vid获取订单列表
    //当前登录商家只能查看自己的商家订单列表
    //if(fields.id != loginStatus.vid){
    //  return F.returnMsg(400,'您无权查看其它商家数据！',1);
    //}
    fields.page = !!fields.page ? parseInt(fields.page):1;
    fields.pageSize = !!fields.pageSize ? parseInt(fields.pageSize):10;
    let queryObj = _.pick(fields,"page","pageSize","id","mobile","orderid","order_code","wareName");
    let  order = require('./o2o/order/order_list');
    return  yield order.order_list(queryObj);
  }else if(act == 2){//通过orderid获取订单详情
    let queryObj = _.pick(fields,"id");
    let  order = require('./o2o/order/order_detail');
    return  yield order.order_detail(queryObj);
  }else if(act ==3){ //根据订单id获取用户瓷肌券列表
    fields.page = !!fields.page ? parseInt(fields.page):1;
    fields.pageSize = !!fields.pageSize ? parseInt(fields.pageSize):10;
    let queryObj = _.pick(fields,"id","page","pageSize");
    let  cj_coupon = require('./o2o/order/coupon_list');
    return  yield cj_coupon.coupon_list(queryObj);
  }else if(act ==4){ //根据瓷肌券码获取瓷肌券详情
    //验证是否为店长操作
    loginStatus ={uid:1498,vendorType:2,primary:0,name:'张飞',vid:56,roleName:'店长',groupid:10}; //模拟的登录店长数据
    if(!(loginStatus.roleName =='店长')){
          return F.returnMsg(400,'未授权的角色，只有店长才有权限操作！',1);
    }
    fields.vid = loginStatus.vid;
    fields.uid = loginStatus.uid;
    let cj_coupon = require('./o2o/order/coupon_detail');
    let queryObj = _.pick(fields,'ticket_code','vid','uid');
    return yield cj_coupon.coupon_detail(queryObj);
  }else if(act ==5){

  }else if(act ==6){//获取商家已验证的瓷肌券列表记录
    fields.page = !!fields.page ? parseInt(fields.page):1;
    fields.pageSize = !!fields.pageSize ? parseInt(fields.pageSize):10;
    fields.status =1;
    if(fields.type==undefined || !_.v.isInt(fields.type) || !_.v.isIn(fields.type,[1,2])){
      return F.returnMsg(400,'type参数必须存在且为1或2！',1);
    }
    if(fields.type ==2){
       if(!fields.id){
         return F.returnMsg(400,'id参数必须存在且为整数！',1);
       }
      //验证登录商家的vid和传递id是否一致
      //if(fields.id != loginStatus.vid){
      //  return F.returnMsg(400,'您无权查看其它商家数据！',1);
      //}
    }
    let cj_coupon = require('./o2o/order/coupon_order_list');
    let queryObj = _.pick(fields,"id","time","type","ticket_code","status","page","pageSize");

    return  yield cj_coupon.coupon_order_list(queryObj);
  }else if(act ==7){

  }

}
